package com.hqyj.demo.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.hqyj.demo.entity.Goods;
import com.hqyj.demo.entity.Purchase;
import com.hqyj.demo.entity.Sale;
import com.hqyj.demo.entity.vo.PurchaseOrSaleVo;
import com.hqyj.demo.entity.vo.PurchaseVo;
import com.hqyj.demo.service.SaleService;
import com.hqyj.demo.utils.HttpStatus;
import com.hqyj.demo.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sale")
public class SaleController {

    @Autowired
    private SaleService saleService;

    //带分页模糊查询
    @PostMapping("/queryPageLike")
    public R queryPageLike(@RequestBody PurchaseOrSaleVo saleVo) {
        if (saleVo != null) {
            System.out.println (saleVo);
            return saleService.selectPageLike (saleVo);
        } else {
            return R.error (HttpStatus.UNSUPPORTED_TYPE);
        }
    }

    //根据id查询单据中详细信息，包含商品信息
    @PostMapping("/queryPurById/{id}")
    public R queryPurById(@PathVariable Integer id) {
        if (id != null) {
            return R.ok ().message ("获取入库单据详情成功!").data ("purchaseOfId",saleService.selectById (id));
        } else {
            return R.error (HttpStatus.UNSUPPORTED_TYPE);
        }
    }

    //初始化进货入库页面
    @PostMapping("/stackPageInit")
    public R stackPageInit() {
        return saleService.stackPageInit();
    }

    //根据类型查询商品
    @PostMapping("/queryByTypeGoods/{typeId}")
    public R queryByTypeGoods(@PathVariable Integer typeId) {
        if (typeId != null) {
            return saleService.queryByTypeGoods(typeId);
        } else {
            return R.error (HttpStatus.UNSUPPORTED_TYPE);
        }
    }

    //添加一个单据
    @PutMapping("/save")
    public R save(@RequestBody Map<String,Object> datas) {
        List<Goods> goodsList = (List<Goods>)datas.get ("goodsList");
        //直接进行此种类型转换则会报文中标题的异常，应进行相应的处理
        //Purchase purchase = (Purchase)datas.get ("purchase");
        //处理如下
        Object docNoObj = datas.get ("purchase");
        ObjectMapper mapper=new ObjectMapper();
        mapper.registerModule (new JavaTimeModule ());
        Sale sale = mapper.convertValue(docNoObj, Sale.class);;
        if (sale != null && goodsList != null) {
            Boolean res = saleService.saveSale (sale,goodsList);
            if (res) {
                return R.ok ().message ("保存单据信息成功");
            } else return R.error ().message ("保存单据信息失败");
        }
        return R.error (HttpStatus.UNSUPPORTED_TYPE).message ("错误数据");
    }

}
